package com.saifan.wyy_ov.ui.property;

import android.Manifest;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.saifan.wyy_ov.R;
import com.saifan.wyy_ov.config.Api;
import com.saifan.wyy_ov.data.bean.DecorateRequestBean;
import com.saifan.wyy_ov.data.bean.RoomInfoBean;
import com.saifan.wyy_ov.model.impl.GetData;
import com.saifan.wyy_ov.model.interfaces.IViewOnClick;
import com.saifan.wyy_ov.ui.album.ui.PhotoAlbumActivity;
import com.saifan.wyy_ov.ui.view.BaseActivity;
import com.saifan.wyy_ov.ui.view.NoScrollGridView;
import com.saifan.wyy_ov.utils.CameraUtil;
import com.saifan.wyy_ov.utils.DateTimePickUtils;
import com.saifan.wyy_ov.utils.DialogUtil;
import com.saifan.wyy_ov.utils.FileUtils;
import com.saifan.wyy_ov.utils.LogUtil;
import com.saifan.wyy_ov.utils.StringUtil;
import com.saifan.wyy_ov.utils.ToastUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

/**
 * @version V1.0.0
 * @author: lomasky
 * @date: 2015-5-13 14:48:42
 * @descrption 装修申请
 */

public class DecorationApplyActivity extends BaseActivity implements CompoundButton.OnCheckedChangeListener {
    private static final int SELECTED_PROPERTY_CONTACTS = 1;
    private static final int SELECTED_DECORATE_CONTACTS = 2;
    private static final int SELECTED_FILE = 3;


    private int ZXSQ_ZXLX = 0;
    private ArrayList<String> selectList;
    private CommentsPicAdapter adapter;
    private final int SELECT_IMG = 0;
    private final int SELECT_PHOTO_TAKEPHOTO = 4;

    private String picName = "";
    private String fileName = "";

    private int selectPostion = 0;
    private RoomInfoBean roomInfoBean;
    private Toolbar toolbar;
    private RadioButton radioButton1;
    private RadioButton radioButton2;
    private RadioGroup radiogroup;
    private EditText contacts;
    private EditText tel;
    private EditText ZXSQZXGS;
    private EditText ZXSQZXFZR;
    private EditText ZXSQZXGSDH;
    private TextView ZXSQQSSJ;
    private TextView ZXSQJZSJ;
    private NoScrollGridView picgrid;
    private ImageView beginDate;
    private ImageView endDate;
    private DecorateRequestBean requestBean;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        roomInfoBean = getRoomInfoBean();
        selectList = new ArrayList<String>();
        setContentView();

    }

    public void setContentView() {
        setContentView(R.layout.activity_decoration_apply);
        this.picgrid = (NoScrollGridView) findViewById(R.id.pic_grid);
        this.endDate = (ImageView) findViewById(R.id.endDate);
        this.ZXSQJZSJ = (TextView) findViewById(R.id.ZXSQ_JZSJ);
        this.beginDate = (ImageView) findViewById(R.id.beginDate);
        this.ZXSQQSSJ = (TextView) findViewById(R.id.ZXSQ_QSSJ);
        this.ZXSQZXGSDH = (EditText) findViewById(R.id.ZXSQ_ZXGSDH);
        this.ZXSQZXFZR = (EditText) findViewById(R.id.ZXSQ_ZXFZR);
        this.ZXSQZXGS = (EditText) findViewById(R.id.ZXSQ_ZXGS);
        this.tel = (EditText) findViewById(R.id.tel);
        this.contacts = (EditText) findViewById(R.id.contacts);
        this.radiogroup = (RadioGroup) findViewById(R.id.radiogroup);
        this.radioButton2 = (RadioButton) findViewById(R.id.radioButton2);
        this.radioButton1 = (RadioButton) findViewById(R.id.radioButton1);
        this.toolbar = (Toolbar) findViewById(R.id.toolbar);


        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        radioButton1.setOnCheckedChangeListener(this);
        radioButton2.setOnCheckedChangeListener(this);

        adapter = new CommentsPicAdapter(selectList, this);
        picgrid.setAdapter(adapter);
        picgrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (selectList.size() < 5) {
                    selectPostion = position - 1;
                    showSelectImgDialog(position == 0 ? false : true, position - 1);
                } else {
                    selectPostion = position;
                    showSelectImgDialog(true, position);
                }
            }
        });


        tel.setText(StringUtil.returnShow(roomInfoBean.getWYKHDA_SJ()));
        contacts.setText(StringUtil.returnShow(roomInfoBean.getWYKHDA_KHMC()));

    }

    //指定开始时间
    public void specialBeginDate(View view) {
        DateTimePickUtils.showAllowTimeout(this, new IViewOnClick() {
            @Override
            public void onClick(Object... object) {

                ZXSQQSSJ.setText(object[0].toString().substring(0, 10));
            }
        }, new Date());
    }

    //指定结束时间
    public void specialEndDate(View view) {


        DateTimePickUtils.showAllowTimeout(this, new IViewOnClick() {
            @Override
            public void onClick(Object... object) {
                ZXSQJZSJ.setText(object[0].toString().substring(0, 10));
            }
        }, new Date());
    }


    //选择装修业主电话
    public void getPropertyContacts(View view) {
        if (Build.VERSION.SDK_INT >= 23) {
            int checkCallPhonePermission = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS);
            if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_CONTACTS}, SELECTED_PROPERTY_CONTACTS);
                return;
            } else {
                Intent i = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
                startActivityForResult(i, SELECTED_PROPERTY_CONTACTS);

            }
        } else {
            Intent i = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
            startActivityForResult(i, SELECTED_PROPERTY_CONTACTS);
        }


    }

    //选择装修公司电话
    public void getDecorateContacts(View view) {

        if (Build.VERSION.SDK_INT >= 23) {
            int checkCallPhonePermission = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS);
            if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_CONTACTS}, SELECTED_DECORATE_CONTACTS);
                return;
            } else {
                Intent i = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
                startActivityForResult(i, SELECTED_DECORATE_CONTACTS);

            }
        } else {
            Intent i = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
            startActivityForResult(i, SELECTED_DECORATE_CONTACTS);
        }

    }

    public void submit(View view) {
        if (isEmpty(ZXSQZXGS)) {
            ToastUtil.showToast(this, "请填写装修公司");
            ZXSQZXGS.setFocusable(true);
            return;
        }
        if (isEmpty(ZXSQZXFZR)) {
            ToastUtil.showToast(this, "请填写装修公司负责人");
            ZXSQZXFZR.setFocusable(true);
            return;
        }

        if (isEmpty(ZXSQZXGSDH)) {
            ToastUtil.showToast(this, "请填写装修公司联系电话");
            ZXSQZXGSDH.setFocusable(true);
            return;
        }
        if (isEmpty(ZXSQQSSJ)) {
            ToastUtil.showToast(this, "请填写装修开始时间");
            specialBeginDate(beginDate);
            return;
        }
        if (isEmpty(ZXSQJZSJ)) {
            ToastUtil.showToast(this, "请填写装修结束时间");
            specialEndDate(endDate);

            return;
        }
        if (compressDate(ZXSQQSSJ.getText().toString(), ZXSQJZSJ.getText().toString())) {
            ToastUtil.showToast(this, " 开始时间在结束时间之前，重新选择结束时间");
            return;
        }

        if (selectList.isEmpty()) {
            ToastUtil.showToast(this, "请上传装修图");

            return;
        }
        GetData getData = new GetData();
        RequestParams params = new RequestParams();
        params.addBodyParameter(Api.Decorate.DECORATE, initParams());
        if (selectList.size() > 0) {
            File file = new File(selectList.get(0));
            if (file.exists()) {
                params.addBodyParameter(file.getName(), file);
            }

        }


        getData.getData(Api.Decorate.DECORATE_SUBMIT, params, new RequestCallBack<String>() {
            @Override
            public void onStart() {
                super.onStart();
                DialogUtil.showProgressDialog(DecorationApplyActivity.this, "正在提交");
            }

            @Override
            public void onCancelled() {
                super.onCancelled();
                LogUtil.i("取消请求");
            }

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {

                if (!StringUtil.isNullOrEmpty(responseInfo.result)) {
                    try {
                        JSONObject jsonObject = new JSONObject(responseInfo.result.toString());
                        String code = jsonObject.getString("Code");
                        if (code.equals("200")) {
                            ToastUtil.showToast(DecorationApplyActivity.this, "提交成功");
                            DialogUtil.closeProgressDialog();
                            finish();

                        } else if (code.equals("203")) {
                            DialogUtil.closeProgressDialog();
                            ToastUtil.showToast(DecorationApplyActivity.this, getString(R.string.login_error_tip));
                        } else if (code.equals("204")) {
                            DialogUtil.closeProgressDialog();
                            ToastUtil.showToast(DecorationApplyActivity.this, "用户名已存在 !");
                        } else if (code.equals("202")) {
                            DialogUtil.closeProgressDialog();
                            ToastUtil.showToast(DecorationApplyActivity.this, "保存失败，信息未做修改 !");
                        } else {
                            LogUtil.e(code);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    LogUtil.e("ServerError");
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {
                LogUtil.i(s);
                ToastUtil.showToast(DecorationApplyActivity.this, getString(R.string.network_error));
                DialogUtil.closeProgressDialog();
            }

        });


    }

    private boolean compressDate(String s, String s1) {
        try {
            return new SimpleDateFormat("yyyy-MM-dd").parse(s).after(new SimpleDateFormat("yyyy-MM-dd").parse(s1));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return false;

    }

    private String initParams() {
        requestBean = new DecorateRequestBean();
        requestBean.setXMBS(roomInfoBean.getXMBS());
        requestBean.setZXSQ_FKGXWJ(roomInfoBean.getFKGX_ZJ());
        requestBean.setZXSQ_ZXLX(ZXSQ_ZXLX);
        requestBean.setZXSQ_QSSJ(ZXSQQSSJ.getText().toString());
        requestBean.setZXSQ_JZSJ(ZXSQJZSJ.getText().toString());
        requestBean.setZXSQ_ZXFZR(ZXSQZXFZR.getText().toString());
        requestBean.setZXSQ_ZXGS(ZXSQZXGS.getText().toString());
        requestBean.setZXSQ_ZXGSDH(ZXSQZXGSDH.getText().toString());
        requestBean.setZXSQ_YZXM(contacts.getText().toString());
        requestBean.setZXSQ_YZDH(tel.getText().toString());


        return new Gson().toJson(requestBean);
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
            if (buttonView.getId() == R.id.radioButton1) {
                ZXSQ_ZXLX = 0;
            } else {
                ZXSQ_ZXLX = 1;
            }
            buttonView.setTextColor(Color.RED);
        } else {
            buttonView.setTextColor(Color.BLACK);
        }


    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {


        if (requestCode == SELECT_IMG) {
            if (resultCode == RESULT_OK) {
                this.selectList = data.getStringArrayListExtra("data");
                adapter.list = selectList;
                adapter.notifyDataSetChanged();
            }
        } else if (requestCode == SELECT_PHOTO_TAKEPHOTO) {
            if (resultCode == RESULT_OK) {
                Bitmap bitmap = data.getParcelableExtra("data") ;
                File file = FileUtils. bitmapToFile(bitmap);
                FileUtils.toAlbum(this,file);
                picName=file.getAbsolutePath();

                selectList.clear();
                if (selectPostion == -1) {
                    this.selectList.add(picName);
                } else {
                    this.selectList.set(selectPostion, picName);
                }

                adapter.list = selectList;
                adapter.notifyDataSetChanged();
            }
        } else if (requestCode == SELECTED_PROPERTY_CONTACTS) {
            if (!(resultCode == RESULT_OK)) {
                return;
            }
            if (data == null) {
                return;
            }
            Uri uri = data.getData();
            String name = "";
            String number = "";

            try {
                Cursor cursor = getContentResolver().query(uri, null, null, null, null);
                if (cursor != null && cursor.moveToFirst()) {

                    int contactId = Integer.valueOf(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID)));
                    name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                    if (Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
                        Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId, null, null);
                        if (phones.moveToFirst()) {
                            //遍历所有的电话号码
                            number = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

                        }
                    }

                    tel.setText(number.replace(" ",""));
                    contacts.setText(name);
                }
                cursor.close();
            } catch (Exception e) {

                LogUtil.e(e.toString());
            }


        } else if (requestCode == SELECTED_DECORATE_CONTACTS) {
            if (!(resultCode == RESULT_OK)) {
                return;
            }
            if (data == null) {
                return;
            }
            Uri uri = data.getData();
            String name2 = "";
            String number2 = "";
            try {
                Cursor cursor = getContentResolver().query(uri, null, null, null,
                        null);

                if (cursor != null && cursor.moveToFirst()) {

                    int contactId = Integer.valueOf(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID)));
                    name2 = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                    if (Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
                        Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId, null, null);
                        if (phones.moveToFirst()) {
                            //遍历所有的电话号码
                            number2 = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

                        }
                    }
//
                    cursor.close();
                }
//
                ZXSQZXGSDH.setText(number2.replace(" ",""));
                ZXSQZXFZR.setText(name2);


            } catch (Exception e) {
                LogUtil.e(e.toString());
            }


        } else if (requestCode == SELECTED_FILE) {

            if (resultCode == RESULT_OK) {
                if (data != null) {
                    // Get the URI of the selected file
                    try {
                        Uri uri = data.getData();
                        String path = uri.getPath();
                        selectList.clear();
                        fileName = path;
                        if (fileName != null) {
                            selectList.add(fileName);
                        }


                        if (FileUtils.isImage(FileUtils.getFileFormat(fileName))) {
                            adapter.list = selectList;
                        }
                        adapter.notifyDataSetChanged();

                    } catch (Exception e) {
                        LogUtil.e(e.toString());
                    }


                }
            }

        }
        super.onActivityResult(requestCode, resultCode, data);

    }

    //显示选择图片的对话框
    private void showSelectImgDialog(boolean hasDelete, final int deletePostion) {
        String[] items;
        if (hasDelete)
            items = new String[]{"从文件中选择", "从相册中选择", "拍照", "删除"};
        else
            items = new String[]{"从文件中选择", "从相册中选择", "拍照"};


        AlertDialog dialog = new AlertDialog.Builder(DecorationApplyActivity.this)
                .setTitle("选择装修图")

                .setItems(items, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (which == 0) {
                            selectFile();
                        } else if (which == 1) {
                            selectImg();
                        } else if (which == 3) {
                            selectList.remove(deletePostion);
                            adapter.list = selectList;
                            adapter.notifyDataSetChanged();
                        } else {
                            cammerPermission(SELECT_PHOTO_TAKEPHOTO);
                        }
                        dialog.dismiss();
                    }
                })
                .show();
    }


    public void cammerPermission(int position) {
        if (Build.VERSION.SDK_INT >= 23) {
            int checkCallPhonePermission = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
            int checkCallPhonePermission1 = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);

            if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED ||checkCallPhonePermission1 != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, position);
                return;
            }  else {
                openCamera();
            }
        } else {
            openCamera();

        }

    }

    private void openCamera() {

        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

        startActivityForResult(intent, SELECT_PHOTO_TAKEPHOTO);
    }

    public void selectImg() {

        if (Build.VERSION.SDK_INT >= 23) {
            int checkCallPhonePermission = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);
            if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, SELECT_IMG);
                return;
            } else {
                openAlbum();
            }
        } else {
            openAlbum();
        }


    }

    private void openAlbum() {
        Intent intent = new Intent(DecorationApplyActivity.this, PhotoAlbumActivity.class);
        intent.putStringArrayListExtra("data", selectList);
        intent.putExtra("isSingle", true);
        startActivityForResult(intent, SELECT_IMG);
    }

    public void selectFile() {

        if (Build.VERSION.SDK_INT >= 23) {
            int checkCallPhonePermission = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);
            if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, SELECTED_FILE);
                return;
            } else {
                openFile();
            }
        } else {
            openFile();
        }


    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_decoration_apply, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.history_record) {
            startActivity(DecorationApplyRecordActivity.class);
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == SELECT_PHOTO_TAKEPHOTO) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED&&grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                // Permission Granted
               openCamera();


            } else {
                // Permission Denied
                Toast.makeText(this, "手机权限不足！", Toast.LENGTH_SHORT)
                        .show();

            }
        } else if (requestCode == SELECT_IMG) {

            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Permission Granted
                openAlbum();


            } else {
                // Permission Denied
                Toast.makeText(this, "您禁用本地存储读写", Toast.LENGTH_SHORT)
                        .show();

            }
        } else if (requestCode == SELECTED_FILE) {

            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Permission Granted
                openFile();



        } else {
            // Permission Denied
            Toast.makeText(this, "您禁用本地存储读写", Toast.LENGTH_SHORT)
                    .show();

        }

        } else if (requestCode == SELECTED_PROPERTY_CONTACTS) {

            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Permission Granted
                Intent i = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
                startActivityForResult(i, SELECTED_PROPERTY_CONTACTS);


            } else {
                // Permission Denied
                Toast.makeText(this, "您禁用了读取通讯录权限", Toast.LENGTH_SHORT)
                        .show();

            }
        } else if (requestCode == SELECTED_DECORATE_CONTACTS) {

            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Permission Granted
                Intent i = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
                startActivityForResult(i, SELECTED_DECORATE_CONTACTS);


            } else {
                // Permission Denied
                Toast.makeText(this, "您禁用了读取通讯录权限", Toast.LENGTH_SHORT)
                        .show();

            }
        }


    }

    private void openFile() {
        Intent target = new Intent(Intent.ACTION_GET_CONTENT);
        // The MIME data type filter
        target.setType("*/*");
        // Only return URIs that can be opened with ContentResolver
        target.addCategory(Intent.CATEGORY_OPENABLE);
        // Create the chooser Intent
        Intent intent = Intent.createChooser(target, getString(R.string.chooser_title));
        try {
            startActivityForResult(intent, SELECTED_FILE);
        } catch (ActivityNotFoundException e) {
            // The reason for the existence of aFileChooser
        }
    }
}
